import { createWebHashHistory, createRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import { storeToRefs } from 'pinia'

const routes = [
    {
        path: '/',
        name: 'home',
        component: () => import('@/views/Home.vue')
    },
    {
        path: '/register',
        name: 'register',
        component:  () => import('@/views/Register.vue')
    },
    {
        path: '/login',
        name: 'login',
        component:  () => import('@/views/Login.vue')
    },
    {
        path: '/CreateAricle',
        name: 'createAricle',
        meta:{
            requireAuth: true
        },
        component:  () => import('@/views/CreateAricle.vue')
    },
    {
        path: '/setting',
        name: 'setting',
        meta:{
            requireAuth: true
        },
        component:  () => import('@/views/Setting.vue')
    },
    {
        path: '/article/:article_id',
        name: 'article',
        component:  () => import('@/views/ArticleDetail.vue')
    },
    {
        path: '/editor/:article_id',
        name: 'update_article',
        meta:{
            requireAuth: true
        },
        component:  () => import('@/views/CreateAricle.vue')
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes,
})

router.beforeEach((to) => {
    const store = useUserStore()
    let { userInfo } = storeToRefs(store)
    if (to.meta.requireAuth && !userInfo.value) {
        // 将用户重定向到登录页面
        // router.push('/login')
        return '/login';
      }
  })

export default router